<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-09-01 13:46:36
 * @version $Id$
 */
namespace app\admin\controller;

use think\Request;
use think\Db;
use think\Controller;
use Godok\Org\Auth;
use think\Config;

class Agent extends Base {
    
    function index(){
        // 商户列表
        $keywords = Request()->get('keywords');
		
		$emp_id = request()->param('emp_id');

        $sc_id = request()->param('sc_id');
		
        $sort = Request()->get('sort')?Request()->get('sort'):"shop_id desc";
        $sort_status = Request()->get('sort_status')?Request()->get('sort_status'):"desc";
        $this->assign('sort_status',$sort_status);
        $query = Db::field('s.shop_id,s.shop_name,s.shop_owner,s.shop_address,Date(s.create_time) as create_time,IFNULL(ul.level_name,"-") as level_name, u.id as user_id,u.phone,u.avatar,u.nickname,e.name,e.phone as ephone,SUM(o.order_money) as money,COUNT(o.user_id) as order_nums,sc.sc_name')
        ->table('sdzx_shop')->alias('s')
        ->join('sdzx_user_level ul','s.level=ul.level_id','left')
        ->join('sdzx_shop_category sc','s.sc_id=sc.sc_id','left')
        ->join('sdzx_employee e','s.agent_id=e.id','left')
        ->join('sdzx_user u','s.user_id=u.id')
        ->join('sdzx_order o','o.user_id=s.user_id and o.order_status=100','left')
        ->group('s.user_id')
        ->order($sort);
        if ($keywords) {
        	$query->where("u.nickname like '%{$keywords}%' or u.username like '%{$keywords}%' or s.shop_name like '%{$keywords}%' or s.shop_owner like '%{$keywords}%' or e.name like '%{$keywords}%'");
        }
		if($emp_id){
			if($emp_id == -1){
				$query->where('ISNULL(s.agent_id)');
			}else{
				$query->where('s.agent_id',$emp_id);
			}
		}

        if($sc_id){
            $query->where('sc.sc_id',$sc_id);
        }
		
        $list = $query->paginate('',false,['query'=>Request()->param()]);
        $data['list'] = $list;
		
		// 管家列表
		$data['employee'] = Db::field('e.id,e.name,g.code')
		->table('sdzx_employee')->alias('e')
		->join('sdzx_employee_group_relation r','e.id=r.uid')
		->join('sdzx_employee_group g','r.group_id=g.id')
		->where("g.code='GJ' and e.status=1 and e.deleted=0")
		->select();
		
        $cate = Db::name('shop_category')->order('sc_sort asc')->select();
        $data['cate'] = $cate;
        $data['sc_id'] = $sc_id;
		$this->assign('emp_id',$emp_id?:'');
		return $this->fetch('index',$data);
    }

    public function allot()
    {
    	if (Request()->isPost()) {
    		$param = Request()->param();

            $update = ['agent_id'=>null];
            if ($param['uid'] !== "0") {
                //员工信息
                $employee = DB::name('employee')->where(['id'=>$param['uid'],'deleted'=>0,'status'=>1])->find();
                if (!$employee) {
                    $this->error('配送员不存在或已禁用');
                }
                $update = ['agent_id'=>$employee['id']];
            }
    		

    		$re = Db::name('shop')->where(['shop_id'=>$param['ids']])->update($update);
    		if ($re!==false) {
    			$this->success('操作成功','refresh');
    		}else{
    			$this->error('操作失败');
    		}
    	}else{
	    	$keywords = Request()->get('keywords');
			// 配送人员
			$Query = Db::field('e.id,e.nickname,e.name,e.phone,g.code,count(s.agent_id) as num')
			->table('sdzx_employee')->alias('e')
			->join('sdzx_employee_group_relation r','e.id=r.uid')
			->join('sdzx_employee_group g','r.group_id=g.id')
			->join('sdzx_shop s','e.id=s.agent_id','left')
			->where("g.code='GJ' and e.status=1 and e.deleted=0")
			->group('e.id');

			if ($keywords) {
				$Query->where("e.name like '%{$keywords}%' or e.phone like '%{$keywords}%'");
			}
			$list = $Query->select();
			return $this->fetch('allot',['list'=>$list]);
		}
    }

    /**
     * 添加商户
     * @return [type] [description]
     */
    public function addshop()
    {
        if (Request()->isPost()) {
            $param = Request()->param();
            !$param['phone'] && $this->error('参数错误');

            $has = Db::name('user')->where(['username'=>$param['phone']])->find();
            $has && $this->error('该商户已经存在');

            $userdata = [
                'username' => $param['phone'],
                'phone'    => $param['phone'],
                'status'   => 1
            ];
            Db::startTrans();
            $user_id = Db::name('user')->insertGetId($userdata);
            if (!$user_id) {
                $this->error('添加失败');
                Db::rollback();
            }
            $shopdata = [
                'shop_name'   => $param['shop_name'],
                'user_id'     => $user_id,
                'agent_id'    => $param['agent_id'],
                'shop_no'     => $param['phone'],
                'create_time' => date('Y-m-d H:i:s')
            ];
            $shop_id = Db::name('shop')->insertGetId($shopdata);
            if (!$shop_id) {
                Db::rollback();
                $this->error('添加失败');
            }
            $re = Db::name('user')->where(['id'=>$user_id])->update(['shop_id'=>$shop_id]);
            if ($re!==false) {
                Db::commit();
                $this->success('添加成功');
            }else{
                Db::rollback();
                $this->error('添加失败');
            }
        }else{
            $list = Db::field('e.id,e.nickname,e.name,e.phone,g.code,count(s.agent_id) as num')
            ->table('sdzx_employee')->alias('e')
            ->join('sdzx_employee_group_relation r','e.id=r.uid')
            ->join('sdzx_employee_group g','r.group_id=g.id')
            ->join('sdzx_shop s','e.id=s.agent_id','left')
            ->where("g.code='GJ' and e.status=1 and e.deleted=0")
            ->group('e.id')->select();

            return $this->fetch('',['list'=>$list]);
        }
        
    }

    //修改用户信息
    public function edit(){
       
        if(Request::instance()->isPost()){
            $data = Request::instance()->param();
            $re1 = Db::name('user')->where('id',$data['id'])->setField('phone', $data['phone']);
            if($re1===false){
                $this->error('用户电话修改失败');
            }
            $map = [
                'shop_name'    => $data['shop_name'],
                'shop_owner'   => $data['shop_owner'],
                'shop_address' => $data['shop_address'],
                'sc_id'        => $data['sc_id']
            ];
            $re2 = Db::name('shop')->where('user_id',$data['id'])->update($map);
            if($re2===false){
                $this->error('商户信息修改失败');
            }
            $this->success('修改成功','refresh');
           
        }else{
            $id = request()->param('id');
            $list = Db::field('u.id,u.nickname,u.phone,s.shop_name,s.shop_owner,s.shop_address,s.sc_id')
            ->table('sdzx_user')->alias('u')
            ->join('sdzx_shop s','u.id=s.user_id','left')
            ->where('u.id',$id)
            ->find();

            $cate = Db::name('shop_category')->order('sc_sort asc')->select();
            return $this->fetch('edit',['list'=>$list,'cate'=>$cate]); 
        }
    }
	
	function getByemp(){
		$emp_id = request()->param('emp_id');
		!$emp_id && $this->error('参数错误');
		
		if($emp_id == -1){
			$where = ['agent_id' => ['is null']];
		}else{
			$where = ['agent_id' => $emp_id];
		}
		
		
		$emp_id = request()->param('emp_id');
		
        $sort = Request()->get('sort')?Request()->get('sort'):"shop_id desc";
        $create_time = Request()->get('create_time')?Request()->get('create_time'):"create_time desc";
        $this->assign(['sort'=>$sort,'create_time'=>$create_time]);
		
        $query = Db::field('s.shop_id,s.shop_name,s.shop_owner,s.shop_address,Date(s.create_time) as create_time,u.phone,u.avatar,u.nickname,e.name,e.phone as ephone')
        ->table('sdzx_shop')->alias('s')
        ->join('sdzx_employee e','s.agent_id=e.id','left')
        ->join('sdzx_user u','s.user_id=u.id')
        ->order($sort.',s.'.$create_time);
        
		if($emp_id){
			if($emp_id == -1){
				$query->where('ISNULL(s.agent_id)');
			}else{
				$query->where('s.agent_id',$emp_id);
			}
		}
		
        $list = $query->paginate('',false,['query'=>Request()->param()]);
        $data['list'] = $list;
		
		// 管家列表
		$data['employee'] = Db::field('e.id,e.name,g.code')
		->table('sdzx_employee')->alias('e')
		->join('sdzx_employee_group_relation r','e.id=r.uid')
		->join('sdzx_employee_group g','r.group_id=g.id')
		->where("g.code='GJ' and e.status=1 and e.deleted=0")
		->select();
		
		return $this->fetch('index',$data);
    
	}

    function uplevel(){
        $param = request()->param();
        $re = Db::name('shop')->where(['shop_id'=>['in',$param['ids']]])->update(['level'=>1]);
        if ($re===false) {
            $this->error('操作失败');
        }else{
            $this->success('操作成功');
        }
    }

    function downlevel(){
        $param = request()->param();
        $re = Db::name('shop')->where(['shop_id'=>['in',$param['ids']]])->update(['level'=>0]);
        if ($re===false) {
            $this->error('操作失败');
        }else{
            $this->success('操作成功');
        }
    }
}